<template>
    <view class="content">
        <uv-form label-width="160rpx" :labelStyle="{fontSize:'26rpx'}" :model="datas" :rules="rules" ref="formRef">
            <uv-form-item label="头像：" prop="avatar">
                <uv-input v-model="datas.avatar" :customStyle="{display:'none'}"></uv-input>
                <uv-upload @afterRead="uploadFile2" :fileList="fileList2" :maxCount="1" @delete="delAvatar"></uv-upload>
            </uv-form-item>
            <uv-form-item label="姓名：" prop="name" required>
                <uv-input placeholder="输入真实姓名" v-model="datas.name"></uv-input>
            </uv-form-item>
            <uv-form-item label="性别：" prop="sex" required>
                <uv-radio-group v-model="datas.sex">
                    <uv-radio name="0" label="男"></uv-radio>&nbsp;&nbsp;
                    <uv-radio name="1" label="女"></uv-radio>
                </uv-radio-group>
            </uv-form-item>
            <uv-form-item label="手机号码：" prop="phoneNum" required>
                <uv-input placeholder="输入本人手机号" v-model="datas.phoneNum"></uv-input>
            </uv-form-item>
            <uv-form-item label="所在城市：" prop="cityCategoryId" required>
                <uv-picker ref="picker" v-model="datas.cityCategoryId" :columns="addressList" :loading="loading"
                    keyName="name" @change="changeAddress" @confirm="selectAddress"></uv-picker>
                <uv-list-item :title="datas.cityCategoryId?datas.cityCategoryId:'请选择城市'" link
                    @click="openCity"></uv-list-item>
                <!-- <uv-input placeholder="输入所在城市" v-model="datas.cityCategoryId"></uv-input> -->
            </uv-form-item>
            <uv-form-item label="详细地址：" v-if="datas.cityCategoryId">
                <uv-input placeholder="输入详细地址" v-model="datas.address"></uv-input>
            </uv-form-item>
            <uv-form-item label="驾龄：" prop="deYear" required>
                <uv-number-box max="70" min="0" v-model="datas.deYear" :integer='true'></uv-number-box>
                <!-- <uv-input type="number" placeholder="多少年" v-model="datas.deYear"></uv-input> -->
            </uv-form-item>
            <uv-form-item label="驾驶证件：" prop="dlImg" required>
                <uv-input v-model="datas.dlImg" :customStyle="{display:'none'}"></uv-input>
                <uv-upload @afterRead="uploadFile1" :fileList="fileList1" :maxCount="1" @delete="delPic"></uv-upload>
            </uv-form-item>
            <uv-form-item label="行驶证：" prop="vlImg">
                <uv-input v-model="datas.vlImg" :customStyle="{display:'none'}"></uv-input>
                <uv-upload @afterRead="uploadFile3" :fileList="fileList3" :maxCount="1" @delete="delPic3"></uv-upload>
            </uv-form-item>
            <uv-form-item label="备注：" prop="remark">
                <uv-textarea v-model="datas.remark" placeholder="填写备注"></uv-textarea>
            </uv-form-item>
        </uv-form>
        <uv-button type="primary" shape="circle" @click="submit">提交资料</uv-button>
    </view>
</template>

<script setup lang="ts">
    import { computed, onMounted, ref } from 'vue';
    import { addCoach, getTree } from "@/src/api/index"
    import { useAuthStore } from '../../stores/auth';
    import config from "@/src/config/index.ts"
    import {
        getToken
    } from "@/src/utils/local";
    const fileList1 = ref([

    ])
    const fileList2 = ref([

    ])
    const fileList3 = ref([

    ])
    const delPic = (event) => {
        fileList1.value.splice(event.index, 1);
        datas.value.dlImg = '';
        console.log(event)
    }
    const delPic3 = (event) => {
        fileList3.value.splice(event.index, 1);
        datas.value.vlImg = '';
        console.log(event)
    }
    const delAvatar = (event) => {
        fileList2.value.splice(event.index, 1);
        datas.value.avatar = '';
        console.log(event)
    }
    //驾驶证上传
    const uploadFile1 = (file) => {
        console.log(file.file.url)
        uni.uploadFile({
            url: config.baseUrl + '/sys/common/upload',
            filePath: file.file.url,
            header: {
                'X-Access-Token': getToken()
            },
            name: "file",
            success: (res) => {
                console.log(JSON.parse(res.data).message)
                fileList1.value.push({
                    url: config.baseUrl + 'sys/common/static/' + JSON.parse(res.data).message
                })
                //添加数据
                datas.value.dlImg = JSON.parse(res.data).message;
                //console.log(config.baseUrl + 'sys/common/static/' + JSON.parse(res.data).message)
            },
            fail: (r) => {
                console.log(r)
            }
        })
    }
    //行驶证上传
    const uploadFile3 = (file) => {
        console.log(file.file.url)
        uni.uploadFile({
            url: config.baseUrl + '/sys/common/upload',
            filePath: file.file.url,
            header: {
                'X-Access-Token': getToken()
            },
            name: "file",
            success: (res) => {
                console.log(JSON.parse(res.data).message)
                fileList3.value.push({
                    url: config.baseUrl + 'sys/common/static/' + JSON.parse(res.data).message
                })
                //添加数据
                datas.value.vlImg = JSON.parse(res.data).message;
                //console.log(config.baseUrl + 'sys/common/static/' + JSON.parse(res.data).message)
            },
            fail: (r) => {
                console.log(r)
            }
        })
    }
    //头像上传
    const uploadFile2 = (file) => {
        console.log(file.file.url)
        uni.uploadFile({
            url: config.baseUrl + '/sys/common/upload',
            filePath: file.file.url,
            header: {
                'X-Access-Token': getToken()
            },
            name: "file",
            success: (res) => {
                console.log(JSON.parse(res.data).message)
                fileList2.value.push({
                    url: config.baseUrl + 'sys/common/static/' + JSON.parse(res.data).message
                })
                //添加数据
                datas.value.avatar = JSON.parse(res.data).message;
                //console.log(config.baseUrl + 'sys/common/static/' + JSON.parse(res.data).message)
            },
            fail: (r) => {
                console.log(r)
            }
        })
    }
    const checkPhone = (rule, value, callback) => {
        // 手机号验证
        if (!value) {
            return callback(new Error("手机号不能为空"));
        } else {
            const reg = /^1[3456789]\d{9}$/;
            if (reg.test(value)) {
                callback();
            } else {
                return callback(new Error("请输入正确的手机号"));
            }
        }
    };
    const rules = ref({
        'name': [
            {
                type: "string",
                required: true,
                message: '请填写姓名',
                trigger: 'blur'
            }
        ],
        'phoneNum': [
            {
                type: "string",
                required: true,
                trigger: 'blur',
                validator: checkPhone,
            }
        ],
        'sex': [
            {
                type: "string",
                required: true,
                trigger: 'blur',
                message: '请填选择性别',
            }
        ],
        'cityCategoryId': [
            {
                type: "string",
                required: true,
                message: '请填写所在城市',
                trigger: 'blur'
            }
        ],
        'deYear': [
            {
                type: "number",
                required: true,
                message: '请填写驾龄',
                trigger: 'blur'
            }
        ],
        'dlImg': [
            {
                type: "string",
                required: true,
                message: '请上传驾驶证',
                trigger: 'blur'
            }
        ],
        // 'vlImg': [
        //     {
        //         type: "string",
        //         required: true,
        //         message: '请上传行驶证',
        //         trigger: 'blur'
        //     }
        // ]
    });
    const formRef = ref(null);
    const datas = ref({
        "cityCategoryId": "",
        "deYear": 0,
        "dlImg": "",
        "name": '',
        "phoneNum": "",
        "remark": "",
        "userId": '',
        "sex": '0',
        "avatar": '',
        "vlImg": '',
        "address": ''
    });
    onMounted(() => {
        authStore.login();
        datas.value.userId = useAuthStore().userInfo.id;

        // formRef.value.form.setRules(rules)
    })
    const picker = ref(null);
    const provinces = ref([]);
    const citys = ref([]);
    const areas = ref([]);
    const loading = ref(true);
    const pickerValue = ref([0, 0, 0]);//选中的地址坐标
    //const defaultValue = ref([510000, 510100, 510104]);
    const addressList = computed(() => {
        console.log('change', provinces.value)
        return [provinces.value, citys.value, areas.value]
    })
    //获取联动数据
    const getData = () => {
        getTree({ code: "SC" }).then(res => {
            if (res.success) {
                provinces.value = res.result;
                //sort((left, right) => (Number(left.code) > Number(right.code) ? 1 : -1));
                handlePickValueDefault();
                console.log(222333, provinces.value)
                loading.value = false;
            }
            console.log(res)
        })
    }
    const openCity = () => {
        console.log(2123)
        getData();
        picker.value.open();
    }
    const handlePickValueDefault = () => {
        // provinces.value = provinces.value[0];
        //设置市
        citys.value = provinces.value[pickerValue.value[0]]?.children || [];
        //设置区
        areas.value = citys.value[pickerValue.value[1]]?.children || [];
        console.log(666, pickerValue.value[1])
        // 设置省
        // pickerValue.value[0] = provinces.value.findIndex(item => Number(item.id) === defaultValue.value[0]);


        // // 设置市
        // citys.value = provinces.value[pickerValue.value[0]]?.children || [];
        // pickerValue.value[1] = citys.value.findIndex(item => Number(item.id) === defaultValue.value[1]);
        // // 设置区
        // areas.value = citys.value[pickerValue.value[1]]?.children || [];
        // pickerValue.value[2] = areas.value.findIndex(item => Number(item.id) === defaultValue.value[2]);
        // // 重置下位置
        //picker.value.setIndexs([pickerValue.value[0], pickerValue.value[1], pickerValue.value[2]], true);
    };
    const changeAddress = (e) => {
        //设置选中的地址
        pickerValue.value = e.indexs;
        //选择省重置市县
        if (e.columnIndex == 0) {
            picker.value.setIndexs([pickerValue.value[0], 0, 0], true);
        }
        //选择城市重置区县
        if (e.columnIndex == 1) {
            picker.value.setIndexs([pickerValue.value[0], pickerValue.value[1], 0], true);
        }

        handlePickValueDefault();
        console.log(e)
    }
    const selectAddress = (e) => {
        datas.value.cityCategoryId = e.value.map(item => { return item.name }).toString()
        console.log(datas.value)
    }
    const authStore = useAuthStore();
    const submit = () => {
        formRef.value.validate().then(res => {
            if (res) {
                //组合地址
                const addr = datas.value.cityCategoryId + ',' + datas.value.address;
                datas.value.cityCategoryId = addr;
                addCoach(datas.value).then(res => {
                    if (res.success) {
                        uni.showToast({
                            icon: "none",
                            title: "提交成功"
                        })
                        //更新角色信息(获取新token)
                        authStore.login();
                        //返回上个页面
                        uni.navigateBack();
                    }
                })
            }
        }).catch(error => {
            console.log(error)
        })

    }
</script>

<style scoped lang="scss">
    .content {
        padding: 30rpx 50rpx;
    }
</style>